import 'common/util/math.js';
import BaseTable from './BaseTable/BaseTable.vue';
import BaseInfo from './BaseInfo/BaseInfo.vue';
import BudgetList from './BudgetList/BudgetList.vue';
import CompletePictures from './CompletePictures/CompletePictures.vue';
import Supplement from './Supplement/Supplement.vue';

export default {
    name: 'acceptApplication',
    components: {
        BaseTable,
        BaseInfo,
        CompletePictures,
        BudgetList,
        Supplement
    },
    provide() {
        return {
            CheckApplication: this
        };
    },
    async created() {
        const { data = [] } = await this.$httpExt().get('/api/common/getSelections', {
            pkeyPath: 'BisArguSetting.pssp.orderStatus'
        });
        this.orderStatusMap = data.reduce((pre, cur) => {
            pre[cur.value] = cur.label;
            return pre;
        }, {});
    },
    data() {
        return {
            orderStatusMap: {},
            formSearch: {
                projectName: '',
                workOrderNo: ''
            },
            isModify: false,
            materialsData: [],
            activeNames: [0, 1, 2, 3],
            collapseConfig: [
                {
                    label: '工单基本信息',
                    comp: 'BaseInfo'
                },
                {
                    label: '完工照片&竣工图',
                    comp: 'CompletePictures'
                },
                {
                    label: '预算清单',
                    comp: 'BudgetList'
                },
                {
                    label: '补充项',
                    comp: 'Supplement'
                }
            ],
            formConfig: [
                {
                    label: '工单编号',
                    prop: 'workOrderNo'
                },
                {
                    label: '工程名称',
                    prop: 'projectName'
                }
            ],
            detailBtns: [
                { label: '取消', type: '', click: this.cancel },
                { label: '保存', type: 'primary', click: this.save },
                { label: '提交', type: 'primary', click: this.submit }
            ],
            detailFormConfig: [
                {
                    label: '工单编号',
                    prop: 'workOrderNo'
                },
                {
                    label: '网点代码',
                    prop: 'orderDept'
                },
                {
                    label: '工程名称',
                    prop: 'constructionProjectName'
                }
            ],
            detailFormSearch: {
                orderNo: '',
                siteCode: '',
                projctName: ''
            },
            orderTitle: '选择工单',
            detailDialog: false,
            chooseDialog: false,
            currentRow: null,
            curSelectedOrder: null,
            currentRowIndex: 0,
            orderTableData: [],
            orderDetail: {
                acceptancePrice: '',
                acceptancePriceExceptTax: '',
                approvalOpinion: '',
                createEmp: '',
                createTime: '',
                fileList: [],
                followUpEmp: '',
                followUpPhone: '',
                id: '',
                invoiceTaxRate: '',
                projectAddress: '',
                projectApprove: '',
                projectApproveExceptTax: '',
                projectBudget: '',
                projectBudgetExceptTax: '',
                projectDeclare: '',
                projectDeclareExceptTax: '',
                projectName: '',
                renovationTotalArea: '',
                status: '',
                supplementList: [],
                templateList: [],
                updateEmp: '',
                updateTime: '',
                workOrderId: 0,
                workOrderNo: '',
                workOrderStatus: 0
            },
            orderTableConfig: [
                { type: 'radio', label: '' },
                {
                    label: '状态',
                    prop: 'status',
                    formatter: val => {
                        const statusMap = {
                            1: '草稿',
                            2: '已提交',
                            3: '已驳回',
                            4: '已通过'
                        };
                        return statusMap[val];
                    }
                },
                { label: '工单编号', prop: 'workOrderNo' },
                { label: '工程名称', prop: 'projectName', showTips: true },
                { label: '工程地址', prop: 'projectAddress', showTips: true },
                { label: '施工面积（M2）', prop: 'renovationTotalArea' },
                { label: '工程验收总造价（元）', prop: 'acceptancePrice' },
                { label: '创建人', prop: 'createEmp' },
                { label: '创建时间', prop: 'createTime' },
                { label: '最后修改人', prop: 'updateEmp' },
                { label: '最后修改时间', prop: 'updateTime' }
            ],
            accptancePager: {
                current: 0,
                pageSize: 10
            },
            ordersPager: {
                current: 0,
                pageSize: 10
            },
            orderDetailTableData: [],
            orderDetailTableCfg: [
                { type: 'radio', width: 40 },
                {
                    label: '状态',
                    prop: 'orderStatus',
                    formatter: val => {
                        return this.orderStatusMap[val];
                    }
                },
                { label: '工单编号', prop: 'orderNo' },
                { label: '工程名称', prop: 'constructionProjectName', showTips: true },
                { label: '工程地址', prop: 'constructionProjectAddress', showTips: true },
                { label: '施工面积（M2）', prop: 'constructionProjectArea' }
            ]
        };
    },
    computed: {
        btns() {
            return [
                { label: '新增', click: this.add },
                { label: '修改', click: this.modify },
                { label: '下载', click: this.down }
            ];
        }
    },
    mounted() {
        this.initTaxReact();
    },
    methods: {
        initTaxReact() {
            this.$root.$on('calcTaxRate', () => {
                const taxMap = { 1: 0, 2: 1, 3: 3, 4: 6, 5: 9 };
                const { invoiceTaxRate, supplementList = [], templateList = [] } = this.orderDetail;
                const label = taxMap[invoiceTaxRate || 1];
                let projectBudget = 0, // 预算总造价
                    declareProjectBudget = 0, // 申报总造价
                    examineProjectBudget = 0; // 审批总造价

                templateList.forEach(v => {
                    projectBudget += Number(v.totalPrice);
                    declareProjectBudget += Number(v.declareTotalPrice);
                    examineProjectBudget += Number(v.examineTotalPrice);
                });
                supplementList.forEach(v => {
                    projectBudget += Number(v.totalPrice);
                    declareProjectBudget += Number(v.declareTotalPrice);
                    examineProjectBudget += Number(v.examineTotalPrice);
                });

                this.orderDetail.projectBudgetExceptTax = projectBudget.toFixed(2) || 0;
                this.orderDetail.projectDeclareExceptTax = declareProjectBudget.toFixed(2) || 0;
                this.orderDetail.projectApproveExceptTax = examineProjectBudget.toFixed(2) || 0;

                this.orderDetail.projectBudget = (projectBudget * ((100 + Number(label)) / 100)).toFixed(2);
                this.orderDetail.declareProjectBudget = (declareProjectBudget * ((100 + Number(label)) / 100)).toFixed(
                    2
                );
                this.orderDetail.examineProjectBudget = (examineProjectBudget * ((100 + Number(label)) / 100)).toFixed(
                    2
                );
            });
        },
        async init(param) {
            const res = await this.$httpExt().post('/api/acceptance/queryAcceptanceByProject', param);

            this.orderTableData = res.data || [];
        },
        cancel() {
            this.chooseDialog = false;
        },
        async initOrders(param) {
            const { current } = this.ordersPager;
            this.ordersPager.pageNum = current;
            const params = { ...param, ...this.ordersPager };
            const orders = await this.$httpExt().post('/api/common/selectOrder', params);

            this.orderDetailTableData = orders.data?.list || [];
        },
        async add() {
            this.detailDialog = true;
        },
        async queryAcceptanceDetail(row = {}) {
            const res = await this.$httpExt().post('/api/acceptance/queryAcceptanceDetail', {
                workOrderNo: row[this.isModify ? 'workOrderNo' : 'orderNo']
            });
            const ret = res.data || {};

            this.orderDetail = ret;
            this.$root.$emit('calcTaxRate');
        },
        searchHttp() {
            this.init({
                current: this.accptancePager.current,
                pageSize: this.accptancePager.pageSize,
                ...this.formSearch
            });
        },
        modify() {
            if (!this.rowSelected()) return;
            this.chooseDialog = true;
            this.isModify = true;

            this.queryAcceptanceDetail(this.currentRow);
        },
        closeChooseDialog() {
            this.isModify = false;
        },
        rowSelected() {
            if (!this.currentRow) {
                this.$message({
                    type: 'info',
                    message: '请选择一条工单'
                });
                return false;
            }
            return true;
        },
        async down() {
            if (!this.rowSelected()) return;
            const { workOrderNo } = this.currentRow;
            const res = await this.$httpExt().post('/api/acceptance/downloadBudget', workOrderNo, {
                responseType: 'blob'
            });
            const bolb = new Blob([res.data]);
            let link = document.createElement('a'); //创建a标签
            //URL.createObjectURL()静态方法会创建一个DOMString
            link.href = window.URL.createObjectURL(bolb);
            link.download = `${Date.now()}.pdf`;
            link.click();
            link.remove();
        },
        choose() {
            if (!this.curSelectedOrder) {
                this.$message({
                    type: 'info',
                    message: '请选择一项内容'
                });
                return false;
            }
            this.queryAcceptanceDetail(this.curSelectedOrder);
            this.chooseDialog = true;
        },
        async save() {
            this.sendOperation(true);
        },
        async sendOperation(isSave) {
            let key = isSave ? 'saveAcceptance' : 'submitAcceptance',
                message = isSave ? '保存' : '提交';
            const { CompletePictures } = this.$refs;
            let [{ fileList, builtImg }] = CompletePictures;
            const params = {
                ...this.orderDetail,
                fileList: [...fileList, builtImg]
            };
            const res = await this.$httpExt().post(`/api/acceptance/${key}`, params);
            const { code } = res || {};

            if (code === '200') this.$message({ type: 'success', message: `${message}成功！` });
            else this.$message({ type: 'error', message: `${message}失败！` });
            this.chooseDialog = false;
            this.detailDialog = false;
        },
        async submit() {
            this.sendOperation();
        }
    }
};
